<template>
  <view class="page">
    <view class="main">
      <up-text size="28" color="#2B2626" weight="400" margin="280rpx 0 0 0" text="手机号登录"></up-text>

      <view class="margin-top-xl">
        <u-form :model="formData" ref="formRef">
          <u-form-item>
            <u-input v-model="formData.phone" type="number" placeholder="输入手机号" prefixIcon="+86"
              prefixIconStyle="margin-right:10rpx" placeholderStyle="color:#B7B7B7" border="none" maxlength="11"
              fontSize="32rpx" :customStyle="{
                backgroundColor: 'rgba(217, 217, 217, 0.59)',
                padding: '24rpx 52rpx',
                borderRadius: '50rpx'
              }" />
          </u-form-item>

          <u-form-item class="margin-top-sm">
            <u-input v-model="formData.code" type="number" placeholder="输入验证码" border="none" fontSize="32rpx"
              placeholderStyle="color:#B7B7B7" :customStyle="{
                backgroundColor: 'rgba(217, 217, 217, 0.59)',
                padding: '24rpx 52rpx',
                borderRadius: '50rpx'
              }">
              <template #suffix>
                <u-text :text="codeButtonText" size="16" :color="!formData.phone || formData.phone.length < 11 || countdown > 0
                    ? 'rgba(32, 40, 15, 0.4)'
                    : 'rgba(32, 40, 15, 1)'
                  " @click="sendCode"></u-text>
              </template>
            </u-input>
          </u-form-item>
        </u-form>

        <view class="padding-lr-xl margin-top">
          <u-button type="primary" text="登录" color="#8DB82E" size="large" shape="circle"
            :disabled="!formData.phone || !formData.code" @click="handleLogin" customStyle="height:58px" />
          <u-text text="切换第三方平台" :size="16" align="center" color="#B7B7B7" margin="20rpx 0 0 0"
            @click="goBack"></u-text>
        </view>

        <!-- <view class="agreement margin-top-sm flex justify-center align-center">
          <u-checkbox
            v-model="agreed"
            shape="circle"
            activeColor="#8DB82E"
          >
            <text
              class="text-gray"
              style="font-size: 24rpx"
            >
              我已阅读并同意
              <text
                class="text-red"
                @click.stop="openAgreement('用户协议')"
                >《用户协议》</text
              >
              和
              <text
                class="text-red"
                @click.stop="openAgreement('隐私政策')"
                >《隐私政策》</text
              >
            </text>
          </u-checkbox>
        </view> -->
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { sendSmsCodeApi, smsLoginApi } from '@/api/api';
import { getUserInfoApi } from '@/api/me';
import { setUserInfo } from '@/utils/auth';
const formRef = ref(null);
const formData = ref({
  phone: '',
  code: ''
});

const countdown = ref(0);

const codeButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s后重新发送` : '发送验证码';
});

const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

const sendCode = async () => {
  if (!formData.value.phone || formData.value.phone.length !== 11) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  console.log('发送验证码', !formData.phone, countdown > 0);

  // TODO: 调用发送验证码接口
  const params = {
    phoneNumber: formData.value.phone
  };
  const result = await sendSmsCodeApi(params);
  console.log('发送验证码结果', result);
  if (result.code === 200) {
    startCountdown();
    uni.showToast({
      title: '验证码发送成功',
      icon: 'none'
    });
  } else {
    uni.showToast({
      title: result.msg,
      icon: 'none'
    });
  }
};

const handleLogin = async () => {
  if (!formData.value.phone || !formData.value.code) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }
  // TODO: 调用登录接口
  const params = {
    phoneNumber: formData.value.phone,
    code: formData.value.code
  };
  const result = await smsLoginApi(params);
  console.log('登录结果', result);
  if (result.code === 200) {
    uni.showToast({
      title: '登录成功',
      icon: 'none'
    });
    setUserInfo('token', result.token);
    // 如果是老用户，根据获取用户信息，判断是老师还是家长，跳转到不同的页面
    if (result.exists === 1) {
      getUserInfo();
    } else {
      uni.navigateTo({
        url: '/pages-sub/login/index'
      });
    }
  } else {
    uni.showToast({
      title: result.msg,
      icon: 'none'
    });
  }
};
const getUserInfo = async () => {
  const result = await getUserInfoApi();
  if (result.code === 200) {
    setUserInfo('userInfo', result.data);
    uni.switchTab({
      url: '/pages/index/index'
    });
  }
};
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.page {
  background: #fffefa;
}
</style>
